﻿/**
 * Description：件号工艺数据查看 hooks
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer：longb
 * date: 2025.3.6
 */
const { ref, reactive, nextTick } = Vue
import { commonFetch } from '../../../Scripts/ZsJs/commonFetch.js'
const { ElMessage, ElMessageBox } = ElementPlus

export function useProductWorkflow() {
  //查询条件信息
  const queryInfo = reactive({
    productid: '',
    workflowid: '',
    productname: '',
    workflowname: '',
    productList: [],
    workflowList: [],
    isshowproduct: true,
    isshowworkflow: true,
    userInfo: null,
    label: 'query'
  });
  //件号、工艺信息、工序列表信息
  const mainDataInfoObj = reactive({
    label: 'product',
    productInfo: {},//件号信息
    workflowInfo: {},//工艺信息
    workflowstepTable: [],//工序列表信息
    workflowstepTableSelectRow: null,//工序列表单选行信息
    selectPara: null//回参数用于查询（检测项、工装工具等信息）
  })
  // 检测项、bom、工装及辅材信息
  const otherDataObj = reactive({
    label: 'bom',
    checkitemList: [],
    bomList: [],
    surpassList: [],
    toolList: [],
    auxList: []
  });
  //查询零件号下拉列表信息
  async function getProductList(url) {
    const formData = new FormData();
    formData.append('productName', queryInfo.productname);
    const { tdata, Result } = await commonFetch({
      url: `../../../Ashx/CommonHandler.ashx?action=GetProductSelect`,
      data: formData
    });
    queryInfo.productList = tdata
    queryInfo.isshowproduct = !Result
  }
  //零件号下拉选择事件，并查询工艺路线下拉列表信息
  async function productSelectHandle(value) {
    if (value == undefined) { return; }
    const formData = new FormData();
    formData.append('productName', value);
    formData.append('workflowName', '');
    formData.append('isThisFactory', false);
    formData.append('factoryid', queryInfo.userInfo == null ? '' : queryInfo.userInfo.FactoryID);
    formData.append('factorycode', queryInfo.userInfo == null ? '' : queryInfo.userInfo.FactoryCode);
    const { tdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=GetWorkflowSelect`,
      data: formData
    });
    queryInfo.workflowid = ''
    queryInfo.workflowList = tdata
    queryInfo.isshowworkflow = !Result
    await getProductInfoData();//查询件号信息
  }
  //根据【工艺条件】查询工艺路线下拉列表信息
  async function getWorkflowList() {
    const formData = new FormData();
    formData.append('productName', '');
    formData.append('workflowName', queryInfo.workflowname);
    formData.append('isThisFactory', false);
    formData.append('factoryid', queryInfo.userInfo == null ? '' : queryInfo.userInfo.FactoryID);
    formData.append('factorycode', queryInfo.userInfo == null ? '' : queryInfo.userInfo.FactoryCode);
    const { tdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=GetWorkflowSelect`,
      data: formData
    });
    queryInfo.workflowList = tdata
    queryInfo.isshowworkflow = !Result
  }
  //零件号下拉清除选择事件
  async function productHandleClear() {
    queryInfo.productid = ''
    queryInfo.workflowid = ''
    queryInfo.isshowproduct = true
    queryInfo.isshowworkflow = true
    mainDataInfoObj.productInfo = {}
    mainDataInfoObj.workflowInfo = {}
    mainDataInfoObj.workflowstepTable = []
    otherDataObj.checkitemList = []
    otherDataObj.bomList = []
    otherDataObj.surpassList = []
    otherDataObj.toolList = []
    otherDataObj.auxList = []
  }
  //工艺路线下拉清除选择事件
  async function workflowHandleClear() {
    await productHandleClear()
  }
  //查询零件号信息
  async function getProductInfoData() {
    const formData = new FormData();
    formData.append('ProductInfo', queryInfo.productid);
    const { tdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=getProductInfoData`,
      data: formData
    });
    if (Result) {
      mainDataInfoObj.productInfo = tdata.value[0]
    }
  }
  //查询工艺信息
  async function getProductAndWorkflowData() {
    if (queryInfo.workflowid === undefined || queryInfo.workflowid === '') { return; }
    const formData = new FormData();
    formData.append('workflowid', queryInfo.workflowid);
    const { tdata, rdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=getWorkflowInfoData`,
      data: formData
    });
    if (Result) {
      mainDataInfoObj.workflowInfo = { ...tdata.value[0], ...rdata.value }
    }
    await getWorkflowStepData();
  }
  //查询工序表格table信息
  async function getWorkflowStepData() {
    const formData = new FormData();
    formData.append('workflowid', queryInfo.workflowid);
    formData.append('factoryid', queryInfo.userInfo == null ? '' : queryInfo.userInfo.FactoryID);
    const { tdata, rdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=getWorkflowStepData`,
      data: formData
    });
    if (Result) {
      mainDataInfoObj.workflowstepTable = tdata.value
      mainDataInfoObj.selectPara = rdata.value
    }
  }
  //工序列表table单选行事件
  async function handleWorkflowstepTableCurrentChange(row) {
    mainDataInfoObj.workflowstepTableSelectRow = row
    await handleWorkflowDetailData(row.WORKFLOWSTEPID);
  }
  //查询工艺明细（检测项、Bom、工装工具、辅材、超越单）
  async function handleWorkflowDetailData(workflowstepid) {
    if (mainDataInfoObj.selectPara === null || mainDataInfoObj.selectPara === '') { return; }
    const formData = new FormData();
    formData.append('data', JSON.stringify(mainDataInfoObj.selectPara));
    formData.append('BOMID', mainDataInfoObj.workflowInfo.BOMID);
    formData.append('ProcessNO', mainDataInfoObj.workflowInfo.PROCESS_NO);
    formData.append('ProductInfo', queryInfo.productid);
    formData.append('workflowid', queryInfo.workflowid);
    if (workflowstepid != '') {
      formData.append('workflowstepid', workflowstepid);
      formData.append('workflowstepname', mainDataInfoObj.workflowstepTableSelectRow.WORKFLOWSTEPNAME);
    } else {
      formData.append('workflowstepid', '');
      formData.append('workflowstepname', '');

    }
    const { sdata, rdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=getWorkflowDetailData`,
      data: formData
    });
    if (Result) {
      otherDataObj.checkitemList = sdata.value.checkpoint
      otherDataObj.bomList = sdata.value.bom
      otherDataObj.surpassList = sdata.value.surpass
      otherDataObj.toolList = sdata.value.tool
      otherDataObj.auxList = sdata.value.aux
    }
  }
  //bom 属性维护
  async function handleChangeBomDetailInfo() {
    if (otherDataObj.bomList.length === 0) {
      ElMessage({ type: 'error', message: `无修改的bom明细信息`, grouping: true });
      return;
    }
    const formData = new FormData();
    formData.append('bom', JSON.stringify(otherDataObj.bomList));
    formData.append('APIUserName', queryInfo.userInfo == null ? '' : queryInfo.userInfo.APIUserName);
    formData.append('APIPassword', queryInfo.userInfo == null ? '' : queryInfo.userInfo.APIPassword);
    const { Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=ChangeBomDetailInfo`,
      data: formData
    });
    if (Result) {
      ElMessage({ type: 'success', message: `修改成功`, grouping: true });
    }
  }

  //工艺预览
  async function handleworkFlowViewPrint() {
    if (queryInfo.workflowid === null || queryInfo.workflowid === '') {
      ElMessage({ type: 'error', message: `请选择工艺路线再进行操作`, grouping: true });
      return;
    }
    const formData = new FormData();
    formData.append('ProductDesc', mainDataInfoObj.productInfo.DESCRIPTION);
    formData.append('ProductName', queryInfo.productid);
    formData.append('BomID', mainDataInfoObj.workflowInfo.BOMID);
    formData.append('WorkFlowID', queryInfo.workflowid);
    const { Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=WorkFlowViewPrint`,
      data: formData
    });
    if (Result) {
      window.open('../Print/ContainerInfoPrintForm.aspx', '_blank')
    }
  }
  //工序关联子工艺工序
  const workflowstepRef = ref(null)
  const stepRelevanToSubWFStepObj = reactive({
    dialogVisible: false,
    dataList: null,
    nodeValue: null,
    workflowList: null,
    workflowid: null,
    workflowstepList: [],
    StepIDs: null,
  })
  //【工序关联子工艺工序】按钮事件
  async function handleStepRelevanToSubWFStep() {
    if (mainDataInfoObj.workflowstepTableSelectRow === null) {
      ElMessage({ type: 'error', message: `请选择要查询或维护的信息`, grouping: true });
      return;
    }
    if (mainDataInfoObj.workflowstepTableSelectRow.ChildWorkflow === null) {
      ElMessage({ type: 'error', message: `选择的序非子工艺序`, grouping: true });
      return;
    }
    const workflowInfo = queryInfo.workflowList.filter(item => item.WORKFLOWID === queryInfo.workflowid)[0].WORKFLOWNAME;
    const data = reactive({
      workflowID: queryInfo.workflowid,
      workflowInfo: workflowInfo,
      sonWorkflowID: mainDataInfoObj.workflowstepTableSelectRow.WORKFLOWID,
      sonWorkflowBaseID: mainDataInfoObj.workflowstepTableSelectRow.WORKFLOWBASEID,
      workflowStepName: mainDataInfoObj.workflowstepTableSelectRow.WORKFLOWSTEPNAME,
      workflowStepID: mainDataInfoObj.workflowstepTableSelectRow.WORKFLOWSTEPID
    })
    const formData = new FormData();
    formData.append('data', JSON.stringify(data));
    const { tdata, rdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=GetStepRelevanToSubWFStepData`,
      data: formData
    });
    if (Result) {
      stepRelevanToSubWFStepObj.dataList = rdata.value.data
      stepRelevanToSubWFStepObj.StepIDs = rdata.value.StepIDs
      stepRelevanToSubWFStepObj.workflowList = tdata.value
      stepRelevanToSubWFStepObj.dialogVisible = true
      stepRelevanToSubWFStepObj.workflowstepList = []
    }
  }
  //工艺树形节点点击事件
  async function handleStepRelevanToSubWFStepNodeClick(nodeValue) {
    stepRelevanToSubWFStepObj.nodeValue = nodeValue
  }
  //查询其他子工艺工序信息
  async function handleSonWFOtherWorkflow() {
    const formData = new FormData();
    formData.append('workflowid', stepRelevanToSubWFStepObj.workflowid);
    const { tdata, rdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=GetSonWFOtherWorkflowStepData`,
      data: formData
    });
    if (Result) {
      stepRelevanToSubWFStepObj.workflowstepList = tdata.value
    }
  }
  //【提交选项】按钮
  async function handleSelectWorkflowstepSubmitClick() {
    let rows = workflowstepRef.value.getSelectionRows();
    if (rows.length === 0) { ElMessage({ type: 'error', message: `请确认选择其他版本工艺有工序信息`, grouping: true }); return; }
    if (stepRelevanToSubWFStepObj.nodeValue === null || !stepRelevanToSubWFStepObj.nodeValue.id.includes('key')) { ElMessage({ type: 'error', message: `请选择主工艺子工艺工序`, grouping: true }); return; }
    stepRelevanToSubWFStepObj.workflowstepList.forEach(item => {
      const exist = rows.some(itemm => itemm.WORKFLOWSTEPID === item.WORKFLOWSTEPID);
      if (exist) {
        item.StepID = stepRelevanToSubWFStepObj.nodeValue.id.split(':')[0]
        item.StepInfo = stepRelevanToSubWFStepObj.nodeValue.label.split('(')[0]
      }
    });
  }
  //【保存】按钮
  async function handleStepRelevanToSubWFStepClick() {
    const formData = new FormData();
    formData.append('sondt', JSON.stringify(stepRelevanToSubWFStepObj.workflowstepList));
    formData.append('StepIDs', stepRelevanToSubWFStepObj.StepIDs);
    formData.append('sonWFID', stepRelevanToSubWFStepObj.workflowid);
    formData.append('workflowid', queryInfo.workflowid);
    const { tdata, rdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=SaveStepRelevanToSubWFStepData`,
      data: formData
    });
    if (Result) {
      ElMessage({ type: 'success', message: `保存成功`, grouping: true });
    }
  }

  //部件小阶段
  const smallStageObj = reactive({
    dialogVisible: false,
    dataList: [{ label: '', value: '' }, { label: '后', value: '后' }, { label: '平', value: '平' }, { label: '前', value: '前' }, { label: '附', value: '附' }],
    data: {},
    attrList: []
  })
  //【部件小阶段】按钮事件
  async function handleSmallStageClick() {
    if (queryInfo.productid === null || queryInfo.productid === '') {
      ElMessage({ type: 'error', message: `请选择零件信息再进行操作`, grouping: true });
      return;
    }
    smallStageObj.dialogVisible = true
    smallStageObj.data.productname = queryInfo.productid.split(':')[0]
    smallStageObj.data.productrev = queryInfo.productid.split(':')[1].split('(')[0]
    const productid = queryInfo.productList.filter(item => item.PRODUCTNAME === queryInfo.productid)[0].PRODUCTID;
    const formData = new FormData();
    formData.append('productid', productid);
    const { tdata, rdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=GetSmallStageData`,
      data: formData
    });
    if (Result) {
      smallStageObj.data.attributevalue = rdata.value
      smallStageObj.attrList = tdata.value
    }
  }
  //部件小阶段弹窗【确认】按钮事件
  async function handleSmallStageSubmitClick() {
    const formData = new FormData();
    formData.append('attrList', JSON.stringify(smallStageObj.attrList));
    formData.append('data', JSON.stringify(smallStageObj.data));
    formData.append('APIUserName', queryInfo.userInfo == null ? '' : queryInfo.userInfo.APIUserName);
    formData.append('APIPassword', queryInfo.userInfo == null ? '' : queryInfo.userInfo.APIPassword);
    const { tdata, rdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=SaveSmallStageData`,
      data: formData
    });
    if (Result) {
      ElMessage({ type: 'success', message: `确认成功`, grouping: true });
    }
  }
  //限制信息维护
  const productmateriallistitemMemoMaintObj = reactive({
    tabname: 'first',
    dialogVisible: false,
    dataList: [],
    row: {}
  })
  //【限制信息维护】按钮事件
  async function handleProductmateriallistitemMemoMaintClick() {
    if (mainDataInfoObj.workflowInfo.BOMID === undefined) {
      ElMessage({ type: 'error', message: `请先查询工艺信息再进行操作`, grouping: true });
      return;
    }
    productmateriallistitemMemoMaintObj.dialogVisible = true
    productmateriallistitemMemoMaintObj.row = {}
    const formData = new FormData();
    formData.append('BomID', mainDataInfoObj.workflowInfo.BOMID);
    const { tdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=GetProductmateriallistitem`,
      data: formData
    });
    if (Result) {
      productmateriallistitemMemoMaintObj.dataList = tdata.value
    }
  }
  //限制信息维护弹窗行点击事件
  async function productmateriallistitemMemoMaintRowClick(row) {
    productmateriallistitemMemoMaintObj.row = row
  }
  //限制信息维护弹窗【保存】按钮事件
  async function SaveProductmateriallistitemMemoMaintClick() {
    const formData = new FormData();
    formData.append('data', JSON.stringify(productmateriallistitemMemoMaintObj.row));
    const { tdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=SaveProductmateriallistitem`,
      data: formData
    });
    if (Result) {
      ElMessage({ type: 'success', message: `保存成功`, grouping: true });
    }
  }
  //启用工艺
  async function handleOpenUse() {
    const formData = new FormData();
    formData.append('workflowid', queryInfo.workflowid);
    const { tdata, rdata, Result } = await commonFetch({
      url: `../../../Ashx/ProductWorkflowDataViewVue3PageHandler.ashx?action=UpdateWorkflowStatus`,
      data: formData
    });
    if (Result) {
      ElMessage({ type: 'success', message: `启用成功`, grouping: true });
      mainDataInfoObj.workflowInfo.ISUSE = 0;
      queryInfo.workflowList.forEach(function (obj) {
        if (obj.WORKFLOWID == queryInfo.workflowid) {
          obj.ISUSE = 0
        }
      })
    }
  }

  return {
    queryInfo,
    getProductList,
    getWorkflowList,
    productSelectHandle,
    productHandleClear,
    workflowHandleClear,
    getProductAndWorkflowData,
    mainDataInfoObj,
    otherDataObj,
    handleWorkflowDetailData,
    handleChangeBomDetailInfo,
    workflowstepRef,
    stepRelevanToSubWFStepObj,
    handleStepRelevanToSubWFStep,
    handleSonWFOtherWorkflow,
    handleStepRelevanToSubWFStepNodeClick,
    handleSelectWorkflowstepSubmitClick,
    handleWorkflowstepTableCurrentChange,
    handleStepRelevanToSubWFStepClick,
    handleworkFlowViewPrint,
    productmateriallistitemMemoMaintObj,
    handleProductmateriallistitemMemoMaintClick,
    smallStageObj,
    handleSmallStageSubmitClick,
    handleSmallStageClick,
    productmateriallistitemMemoMaintRowClick,
    SaveProductmateriallistitemMemoMaintClick,
    handleOpenUse
  }
}